package com.sws.web.controller.ry_rongyue.wx;

import com.sws.common.core.domain.AjaxResult;
import com.sws.common.utils.DateUtils;
import com.sws.customer.ball.WxCustomerBinder;
import com.sws.customer.domain.RyCustomer;
import com.sws.reservation.domain.RyReservation;
import com.sws.reservation.service.IRyReservationService;
import com.sws.staff.domain.RyStaff;
import com.sws.staff.mapper.RyStaffMapper;
import com.sws.staff.service.RyStaffWxBinder;
import com.sws.weixin.button.TestButton;
import com.sws.weixin.entity.*;
import com.sws.weixin.mapper.TUser2Mapper;
import com.sws.weixin.service.StaffWxBinder;
import com.sws.weixin.service.TemplateService;
import com.sws.weixin.service.UserMessageService;
import com.sws.weixin.service.WxService;
import com.sws.weixin.service.WxTemplateService;
import com.sws.weixin.token.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;

/**
 * @author Thor
 * @公众号 Java架构栈
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxController {

    @Value("${wx.appid}")
    private String appId;
    
    @Value("${wx.secret}")
    private String secret;
    
    @Value("${redirect.domain}")
    private String redirectDomain;
    
    @Value("${wx.template.reservation-reminder-id:未配置}")
    private String reservationTemplateId;
    
    @Value("${wx.template.AI-reservation-reminder-id:未配置}")
    private String reservationAITemplateId;
    
    @Value("${wx.template.staff-reminder-id:未配置}")
    private String staffReservationTemplateId;

    @Autowired
    private WxService wxService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    @Autowired
    private TestButton testButton;

    @Autowired
    private TUser2Mapper tUser2Mapper;

    @Autowired
    private UserMessageService userMessageService;

    @Autowired
    private WxTemplateService wxTemplateService;

    @Autowired
    private TemplateService templateService;
    
    @Autowired
    private WxCustomerBinder wxCustomerBinder;
    
    @Autowired
    @Qualifier("wxStaffBinderImpl")
    private StaffWxBinder wxStaffBinder; // 微信模块的StaffWxBinder实现
    
    @Autowired
    private RyStaffWxBinder ryStaffWxBinder; // 员工模块的RyStaffWxBinder实现
    
    @Autowired
    private IRyReservationService ryReservationService;
    
    @Autowired
    private RyStaffMapper staffMapper;

    /**
     * 强制刷新微信Token
     */
    @GetMapping("/refresh-token")
    public AjaxResult refreshToken() {
        try {
            String newToken = tokenUtil.forceRefreshToken();
            if (newToken != null && !newToken.isEmpty()) {
                return AjaxResult.success("Token刷新成功", newToken);
            } else {
                return AjaxResult.error("Token刷新失败，请检查日志");
            }
        } catch (Exception e) {
            log.error("刷新Token时发生异常", e);
            return AjaxResult.error("刷新Token时发生异常: " + e.getMessage());
        }
    }
    
    @GetMapping("/hello")
    public String hello(){
        TestAppidSerectVO testAppidSerectVO = wxService.testapplicatio();
        System.out.println(testAppidSerectVO);
        return "hello";
    }
    
    /**
     * 测试配置是否正确注入
     */
    @GetMapping("/config")
    public AjaxResult getConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("appId", appId);
        config.put("secret", secret);
        config.put("redirectDomain", redirectDomain);
        config.put("accessToken", tokenUtil.getAccessToken());
        return AjaxResult.success(config);
    }
    
    /**
     * 测试微信模板配置是否正确注入
     */
    @GetMapping("/template-config")
    public AjaxResult getTemplateConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("reservationTemplateId", reservationTemplateId);
        config.put("reservationAITemplateId", reservationAITemplateId);
        config.put("staffReservationTemplateId", staffReservationTemplateId);
        return AjaxResult.success(config);
    }
    
    /**
     * 创建微信菜单
     */
    @GetMapping("/createMenu")
    public AjaxResult createMenu() {
        String result = testButton.createMenu();
        return AjaxResult.success("菜单创建结果", result);
    }

    /**
     * 消息验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping()
    public String check(String signature,
                        String timestamp,
                        String nonce,
                        String echostr){

        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String token = "qiye";
        List<String> list = Arrays.asList(token, timestamp, nonce);
        //排序
        Collections.sort(list);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : list) {
            stringBuilder.append(s);
        }
        //加密
        try {
            MessageDigest instance = MessageDigest.getInstance("sha1");
            //使用sha1进行加密，获得byte数组
            byte[] digest = instance.digest(stringBuilder.toString().getBytes());
            StringBuilder sum = new StringBuilder();
            for (byte b : digest) {
                sum.append(Integer.toHexString((b>>4)&15));
                sum.append(Integer.toHexString(b&15));
            }
            // 3）开发者获得加密后的字符串可与 signature 对比，标识该请求来源于微信
            if(!StringUtils.isEmpty(signature)&&signature.equals(sum.toString())){
                return echostr;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }



/*
    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        Map<String,String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        try {
            //读取request输入流，获得Document对象
            Document document = reader.read(inputStream);
            //获得root节点
            Element root = document.getRootElement();
            //获取所有的子节点
            List<Element> elements = root.elements();
            for (Element element : elements) {
                map.put(element.getName(),element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        System.out.println(map);
        String msgType = map.get("MsgType");
        String message = "";
        switch (msgType){
            case "text":
                //回复同义词
                if("图文".equals(map.get("Content"))){
                    message = getReplyNewsMessage(map);
                }else{
                    message = getReplyMessageByWord(map);

                }
                break;
            case "event":
                message = handleEvent(map);
                break;
            case "image":
                message = handleImage(map);
                break;
            default:
                break;

        }

//        String message = getReplyMessage(map);
        return message;
    }
*/


    @PostMapping()
    public String receiveMessage(HttpServletRequest request) throws IOException {
        try {
            ServletInputStream inputStream = request.getInputStream();
            return wxService.handleMessage(inputStream,request);

        } catch (IOException | DocumentException e) {
            return e.getMessage();
        }
    }

    /**
     * 拉取用户信息并跳转到注册页面
     *
     * @param code 微信授权码
     * @return 跳转HTML
     */
    @GetMapping("/getSignUpUserInfo")
    public String getSignUpUserInfo(HttpServletRequest request) {
        //获取code
        String code = request.getParameter("code");
        if (code == null || code.isEmpty()) {
            return "<h2>授权失败，缺少必要的授权码</h2>";
        }
        return wxService.getSignUpUserInfo(code);
    }

    @RequestMapping("/getUserInfo")
    public String getUserInfo(HttpServletRequest request) {
        try {
            //获取code
            String code = request.getParameter("code");
            return wxService.getUserInfo(code);
        } catch (IOException | DocumentException e) {
            return e.getMessage();
        }
    }
    
    /**
     * 拉取工作人员顾客管理页面
     */
    @GetMapping("/getStaffManage")
    public String getStaffManage(HttpServletRequest request) {
        //获取code
        String code = request.getParameter("code");
        if (code == null || code.isEmpty()) {
            return "<h2>授权失败，缺少必要的授权码</h2>";
        }
        return wxService.getStaffManage(code);
    }
    
    /**
     * 技师顾客管理页面直接访问
     */
    @GetMapping(value = "/staffManage", produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<String> staffManagePage(HttpServletRequest request) {
        try {
            // 获取openid参数
            String openid = request.getParameter("openid");
            
            // 从classpath中读取HTML文件
            Resource resource = new ClassPathResource("templates/staffManage.html");
            Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            String html = FileCopyUtils.copyToString(reader);
            
            // 将openid插入到HTML中
            if (openid != null && !openid.isEmpty()) {
                html = html.replace("</head>", 
                        "<script>var wxOpenid = \"" + openid + "\";</script>\n</head>");
            }
            
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("无法加载技师顾客管理页面");
        }
    }
    
    /**
     * 拉取顾客预约管理页面
     */
    @GetMapping("/getCustomerReservation")
    public String getCustomerReservation(HttpServletRequest request) {
        //获取code
        String code = request.getParameter("code");
        if (code == null || code.isEmpty()) {
            return "<h2>授权失败，缺少必要的授权码</h2>";
        }
        return wxService.getCustomerReservation(code);
    }
    
    /**
     * 顾客预约管理页面直接访问
     */
    @GetMapping(value = "/customerReservation", produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<String> customerReservationPage(HttpServletRequest request) {
        try {
            // 获取openid参数
            String openid = request.getParameter("openid");
            
            // 从classpath中读取HTML文件
            Resource resource = new ClassPathResource("templates/customerReservation.html");
            Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            String html = FileCopyUtils.copyToString(reader);
            
            // 将openid插入到HTML中
            if (openid != null && !openid.isEmpty()) {
                html = html.replace("</head>", 
                        "<script>var wxOpenid = \"" + openid + "\";</script>\n</head>");
            }
            
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("无法加载顾客预约管理页面");
        }
    }
    
    /**
     * 验证技师身份
     */
    @PostMapping("/verifyStaffIdentity")
    public AjaxResult verifyStaffIdentity(@RequestBody Map<String, String> params) {
        log.info("验证工作人员身份: {}", params);
        String openid = params.get("openid");
        
        if (openid == null || openid.isEmpty()) {
            return AjaxResult.error("缺少参数");
        }
        
        // 优先使用员工模块的实现
        Map<String, Object> staffResult = ryStaffWxBinder.verifyStaffIdentity(openid);
        
        if (Boolean.TRUE.equals(staffResult.get("success"))) {
            // 员工模块验证成功
            return AjaxResult.success("验证成功", staffResult.get("staffInfo"));
        }
        
        // 如果员工模块验证失败，则尝试使用微信模块的实现
        Map<String, Object> wxResult = wxStaffBinder.verifyStaffIdentity(openid);
        
        if (Boolean.TRUE.equals(wxResult.get("success"))) {
            return AjaxResult.success("验证成功", wxResult.get("staffInfo"));
        }
        
        return AjaxResult.error("验证失败，您未绑定工作人员信息或绑定信息有误");
    }
    
    /**
     * 验证顾客身份
     */
    @PostMapping("/verifyCustomerIdentity")
    public AjaxResult verifyCustomerIdentity(@RequestBody Map<String, String> params) {
        try {
            String openid = params.get("openid");
            if (openid == null || openid.trim().isEmpty()) {
                return AjaxResult.error("微信授权信息缺失");
            }
            
            Map<String, Object> result = wxCustomerBinder.verifyCustomerIdentity(openid);
            
            if ((Boolean) result.get("success")) {
                return AjaxResult.success("验证成功", result.get("customerInfo"));
            } else {
                return AjaxResult.error(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("验证顾客身份时出错: " + e.getMessage());
        }
    }
    
    /**
     * 获取技师预约列表
     */
    @PostMapping("/getStaffReservations")
    public AjaxResult getStaffReservations(@RequestBody Map<String, Object> params) {
        try {
            String openid = (String) params.get("openid");
            String staffPid = (String) params.get("staffPid");
            Integer status = params.get("status") != null && !params.get("status").toString().isEmpty() ? 
                Integer.parseInt(params.get("status").toString()) : null;
            
            if (openid == null || staffPid == null) {
                return AjaxResult.error("缺少必要参数");
            }
            
            // 验证技师身份 - 优先使用员工模块的实现
            Map<String, Object> verification = ryStaffWxBinder.verifyStaffIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                verification = wxStaffBinder.verifyStaffIdentity(openid);
                if (!(Boolean) verification.get("success")) {
                    return AjaxResult.error("无效的技师身份");
                }
            }
            
            // 查询预约
            List<RyReservation> reservations = ryReservationService.selectRyReservationByStaffPid(staffPid, status);
            return AjaxResult.success("查询成功", reservations);
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取预约列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取顾客预约列表
     */
    @PostMapping("/getCustomerReservations")
    public AjaxResult getCustomerReservations(@RequestBody Map<String, Object> params) {
        try {
            String openid = (String) params.get("openid");
            String customerPid = (String) params.get("customerPid");
            Integer status = params.get("status") != null && !params.get("status").toString().isEmpty() ? 
                Integer.parseInt(params.get("status").toString()) : null;
            
            if (openid == null || customerPid == null) {
                return AjaxResult.error("缺少必要参数");
            }
            
            // 验证顾客身份
            Map<String, Object> verification = wxCustomerBinder.verifyCustomerIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                return AjaxResult.error("无效的顾客身份");
            }
            
            // 查询预约
            List<RyReservation> reservations = ryReservationService.selectRyReservationByCustomerPid(customerPid, status);
            return AjaxResult.success("查询成功", reservations);
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取预约列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新预约状态（技师）
     */
    @PostMapping("/updateReservationStatus")
    public AjaxResult updateReservationStatus(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.valueOf(params.get("id").toString());
            Integer status = Integer.parseInt(params.get("status").toString());
            String openid = (String) params.get("openid");
            
            // 验证技师身份 - 优先使用员工模块的实现
            Map<String, Object> verification = ryStaffWxBinder.verifyStaffIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                verification = wxStaffBinder.verifyStaffIdentity(openid);
                if (!(Boolean) verification.get("success")) {
                    return AjaxResult.error("无效的技师身份");
                }
            }
            
            // 获取技师信息
            RyStaff staffInfo = (RyStaff) verification.get("staffInfo");
            
            // 更新状态
            int result = ryReservationService.updateReservationStatus(id, status, staffInfo.getPid());
            
            if (result > 0) {
                return AjaxResult.success("更新成功");
            } else {
                return AjaxResult.error("更新失败，可能没有权限或状态流转无效");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("更新预约状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消预约（顾客）
     */
    @PostMapping("/cancelReservation")
    public AjaxResult cancelReservation(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.valueOf(params.get("id").toString());
            String openid = (String) params.get("openid");
            
            // 验证顾客身份
            Map<String, Object> verification = wxCustomerBinder.verifyCustomerIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                return AjaxResult.error("无效的顾客身份");
            }
            
            // 获取顾客信息
            RyCustomer customerInfo = (RyCustomer) verification.get("customerInfo");
            
            // 取消预约
            int result = ryReservationService.cancelReservation(id, customerInfo.getPid());
            
            if (result > 0) {
                return AjaxResult.success("取消成功");
            } else {
                return AjaxResult.error("取消失败，可能没有权限或状态不允许取消");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("取消预约失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建预约（顾客）
     */
    @PostMapping("/createReservation")
    public AjaxResult createReservation(@RequestBody Map<String, Object> params) {
        try {
            String openid = (String) params.get("openid");
            String customerPid = (String) params.get("customerPid");
            String customerName = (String) params.get("customerName");
            String customerPhone = (String) params.get("customerPhone");
            String serviceContent = (String) params.get("serviceContent");
            String appointmentTime = (String) params.get("appointmentTime");
            String staffPid = (String) params.get("staffPid");
            
            // 参数验证
            if (openid == null || customerPid == null || customerName == null || 
                customerPhone == null || serviceContent == null || appointmentTime == null) {
                return AjaxResult.error("缺少必要参数");
            }
            
            // 验证顾客身份
            Map<String, Object> verification = wxCustomerBinder.verifyCustomerIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                return AjaxResult.error("无效的顾客身份");
            }
            
            // 创建预约对象
            RyReservation reservation = new RyReservation();
            reservation.setCustomerPid(customerPid);
            reservation.setCustomerName(customerName);
            reservation.setCustomerPhone(customerPhone);
            reservation.setServiceContent(serviceContent);
            reservation.setStaffPid(staffPid);
            // 如果指定了技师，需要查询技师名称
            if (staffPid != null && !staffPid.isEmpty()) {
                RyStaff queryStaff = new RyStaff();
                queryStaff.setPid(staffPid);
                List<RyStaff> staffList = staffMapper.selectRyStaffList(queryStaff);
                if (!staffList.isEmpty()) {
                    reservation.setStaffName(staffList.get(0).getName());
                }
            }
            // 设置预约时间、状态等信息
            reservation.setAppointmentTime(DateUtils.parseLocalDateTime(appointmentTime));
            reservation.setStatus(1); // 待确认状态
            
            // 保存预约
            int result = ryReservationService.insertRyReservation(reservation);
            
            if (result > 0) {
                return AjaxResult.success("预约创建成功，请等待确认");
            } else {
                return AjaxResult.error("创建预约失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("创建预约失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取技师列表
     */
    @GetMapping("/getStaffList")
    public AjaxResult getStaffList() {
        try {
            RyStaff queryStaff = new RyStaff();
            queryStaff.setIdentity(2); // 假设2表示技师身份
            List<RyStaff> staffList = staffMapper.selectRyStaffList(queryStaff);
            
            // 简化返回的数据，只包含必要字段
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (RyStaff staff : staffList) {
                Map<String, Object> item = new HashMap<>();
                item.put("pid", staff.getPid());
                item.put("name", staff.getName());
                resultList.add(item);
            }
            
            return AjaxResult.success("查询成功", resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取技师列表失败: " + e.getMessage());
        }
    }

    /**
     * 处理用户注册表单提交
     * @param params 包含name、phone和openid的JSON数据
     * @return 处理结果
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody Map<String, String> params) {
        try {
            String name = params.get("name");
            String phone = params.get("phone");
            String openid = params.get("openid");
            
            // 简单的参数验证
            if (name == null || name.trim().isEmpty()) {
                return AjaxResult.error("姓名不能为空");
            }
            
            if (phone == null || !phone.matches("^1\\d{10}$")) {
                return AjaxResult.error("请输入正确的手机号码");
            }
            
            if (openid == null || openid.trim().isEmpty()) {
                return AjaxResult.error("微信授权信息缺失，请重新进入");
            }
            
            // 调用微信服务绑定用户
            Map<String, Object> result = wxService.bindWxUserToCustomer(name, phone, openid);
            
            if ((Boolean) result.get("success")) {
                return AjaxResult.success(result.get("msg").toString());
            } else {
                return AjaxResult.error(result.get("msg").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("处理注册请求时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 直接访问注册页面
     * @return 注册页面HTML内容
     */
    @GetMapping(value = "/register", produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<String> registerPage(HttpServletRequest request) {
        try {
            // 获取openid参数
            String openid = request.getParameter("openid");
            
            // 从classpath中读取HTML文件
            Resource resource = new ClassPathResource("templates/register.html");
            Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            String html = FileCopyUtils.copyToString(reader);
            
            // 将openid插入到HTML中
            if (openid != null && !openid.isEmpty()) {
                html = html.replace("</head>", 
                        "<script>var wxOpenid = \"" + openid + "\";</script>\n</head>");
            }
            
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("无法加载注册页面");
        }
    }


    @PostMapping("/send")
//    @PreAuthorize("@ss.hasPermi('wx:template:send')")
    public AjaxResult sendTemplate(@Validated @RequestBody TemplateSendDTO dto) {
        TUser tUser = tUser2Mapper.selectByPrimaryKey(dto.getTouser());
        UserMessage userMessage = new UserMessage();
        userMessage.setContent(dto.getData().toString());
        userMessage.setOpenid(dto.getTouser());
        userMessage.setAvatarUrl(tUser.getHeadimgurl());
        userMessage.setUserName(tUser.getNickname());
        userMessageService.saveMessage(userMessage);
        return wxTemplateService.sendTemplate(dto);
    }



    @PreAuthorize("@ss.hasPermi('message:template:send')")
    @PostMapping("/batchSend")
    public AjaxResult batchSend(@RequestBody BatchSendDTO dto) {

        int successCount = 0 ;
        for (String openid : dto.getOpenids()) {
            TemplateSendDTO singleDto = new TemplateSendDTO();
            singleDto.setTouser(openid);
            singleDto.setTemplateId(dto.getTemplateId());
            singleDto.setData(dto.getParams());

            AjaxResult result = wxTemplateService.sendTemplate(singleDto);
            if (result.isSuccess()) {
                successCount++;
                TUser tUser = tUser2Mapper.selectByPrimaryKey(openid);
                UserMessage userMessage = new UserMessage();
                userMessage.setContent(dto.getParams().toString());
                userMessage.setOpenid(openid);
                userMessage.setAvatarUrl(tUser.getHeadimgurl());
                userMessage.setUserName(tUser.getNickname());
                userMessageService.saveMessage(userMessage);
            }
        }

        return AjaxResult.success("批量发送完成",successCount);
    }
    
    /**
     * 拉取工作人员信息并跳转到工作人员认证页面
     *
     * @param request 请求
     * @return 跳转HTML
     */
    @GetMapping("/getStaffAuthUserInfo")
    public String getStaffAuthUserInfo(HttpServletRequest request) {
        //获取code
        String code = request.getParameter("code");
        if (code == null || code.isEmpty()) {
            return "<h2>授权失败，缺少必要的授权码</h2>";
        }
        return wxService.getStaffAuthUserInfo(code);
    }
    
    /**
     * 处理工作人员认证表单提交
     * 
     * @param params 包含name、phone和openid的JSON数据
     * @return 处理结果
     */
    @PostMapping("/staffAuth")
    public AjaxResult staffAuth(@RequestBody Map<String, String> params) {
        log.info("工作人员认证: {}", params);
            String name = params.get("name");
            String phone = params.get("phone");
            String openid = params.get("openid");
            
        if (name == null || phone == null || openid == null || 
            name.isEmpty() || phone.isEmpty() || openid.isEmpty()) {
            return AjaxResult.error("参数错误");
            }
            
        // 优先使用员工模块的实现
        Map<String, Object> staffResult = ryStaffWxBinder.bindWxUserToStaff(name, phone, openid);
        
        if (Boolean.TRUE.equals(staffResult.get("success"))) {
            // 员工模块绑定成功
            return AjaxResult.success("认证成功", staffResult);
            }
            
        // 如果员工模块绑定失败，则尝试使用微信模块的实现
        Map<String, Object> wxResult = wxStaffBinder.bindWxUserToStaff(name, phone, openid);
            
        if (Boolean.TRUE.equals(wxResult.get("success"))) {
            return AjaxResult.success("认证成功", wxResult);
        }
        
        return AjaxResult.error(wxResult.get("msg") != null ? wxResult.get("msg").toString() : "认证失败");
    }
    
    /**
     * 访问工作人员认证页面
     * 
     * @return 工作人员认证页面HTML内容
     */
    @GetMapping(value = "/staffAuth", produces = MediaType.TEXT_HTML_VALUE)
    public ResponseEntity<String> staffAuthPage(HttpServletRequest request) {
        try {
            // 获取openid参数
            String openid = request.getParameter("openid");
            
            // 从classpath中读取HTML文件
            Resource resource = new ClassPathResource("templates/staffAuth.html");
            Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            String html = FileCopyUtils.copyToString(reader);
            
            // 将openid插入到HTML中
            if (openid != null && !openid.isEmpty()) {
                html = html.replace("</head>", 
                        "<script>var wxOpenid = \"" + openid + "\";</script>\n</head>");
            }
            
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("无法加载工作人员认证页面");
        }
    }

    @GetMapping("/hello2")
    public String testwxdelete() throws Exception {
        log.info("开始执行微信云端删除：{}","测试消息1");
        templateService.deleteTemplate("fmcCvZksHKQdsCsqJssA8pl0QhwaHGhJTr34NUJIKu4");
        return "hello2";
    }

    /**
     * 获取技师的顾客列表
     */
    @PostMapping("/getStaffCustomers")
    public AjaxResult getStaffCustomers(@RequestBody Map<String, Object> params) {
        log.info("获取技师的顾客列表: {}", params);
        try {
            String openid = (String) params.get("openid");
            String staffPid = (String) params.get("staffPid");
            
            if (openid == null) {
                return AjaxResult.error("缺少必要参数");
            }
            
            // 验证技师身份
            Map<String, Object> verification = ryStaffWxBinder.verifyStaffIdentity(openid);
            if (!(Boolean) verification.get("success")) {
                verification = wxStaffBinder.verifyStaffIdentity(openid);
                if (!(Boolean) verification.get("success")) {
                    return AjaxResult.error("无效的技师身份");
                }
            }
            
            // 如果staffPid为空，从验证结果中获取
            if (staffPid == null || staffPid.isEmpty()) {
                Object staffInfo = verification.get("staffInfo");
                if (staffInfo instanceof RyStaff) {
                    staffPid = ((RyStaff) staffInfo).getPid();
                    log.info("从验证结果中获取staffPid: {}", staffPid);
                } else {
                    log.error("无法获取staffPid，staffInfo类型: {}", staffInfo != null ? staffInfo.getClass().getName() : "null");
                    return AjaxResult.error("无法获取技师ID");
                }
            }
            
            if (staffPid == null || staffPid.isEmpty()) {
                return AjaxResult.error("无法获取技师ID");
            }
            
            // 获取技师的顾客列表 - 优先使用员工模块的实现
            Map<String, Object> staffCustomers = ryStaffWxBinder.getStaffCustomers(staffPid);
            if (!(Boolean) staffCustomers.get("success") || staffCustomers.get("customers") == null) {
                // 尝试微信模块的实现
                staffCustomers = wxStaffBinder.getStaffCustomers(staffPid);
            }
            
            return AjaxResult.success("获取成功", staffCustomers.get("customers"));
            
        } catch (Exception e) {
            log.error("获取技师的顾客列表失败", e);
            return AjaxResult.error("获取技师的顾客列表失败: " + e.getMessage());
        }
    }
}
